package com.apply.service;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author tianp
 */
@Service
public class RedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public String get(String key) {
        if (StringUtils.isNoneEmpty(key)) {
            return redisTemplate.opsForValue().get(key);
        }
        return null;
    }

    public int getInt(String key) {
        String value = get(key);
        if (StringUtils.isEmpty(value)) {
            return -1;
        }
        return Integer.parseInt(value);
    }

    public <T> T get(String key, Class<T> type) {
        String value = get(key);
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        return JSON.parseObject(value, type);
    }

    public void set(String key, String value) {
        if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)) {
            redisTemplate.opsForValue().set(key, value);
        }
    }

    public void set(String key, Object value) {
        if (value != null) {
            set(key, JSON.toJSONString(value));
        }
    }

    public void set(String key, int seconds, String value) {
        if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)) {
            redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
        }
    }

    /**
     * @param key
     * @param seconds
     * @param value
     */
    public void set(String key, int seconds, Object value) {
        if (value != null) {
            set(key, seconds, JSON.toJSONString(value));
        }
    }

    /**
     * 根据key删除
     *
     * @param key
     */
    public void del(String key) {
        if (StringUtils.isNotEmpty(key)) {
            redisTemplate.delete(key);
        }
    }

    public void expire(String key, int seconds) {
        Validate.isTrue(seconds > 0, "second should be gt 0");
        if (StringUtils.isNotEmpty(key)) {
            redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
        }
    }

    public void removeOldToken(String prefix) {
        Validate.isTrue(StringUtils.isNoneEmpty(prefix));
        Set<String> keys = redisTemplate.keys(prefix + "*");
        redisTemplate.delete(keys);
    }
}
